package org.dromara.patrol.service.impl;

import cn.hutool.core.util.ObjectUtil;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.patrol.domain.PatrolReport;
import org.dromara.patrol.domain.PatrolTask;
import org.dromara.patrol.domain.PatrolTemplate;
import org.dromara.patrol.domain.PatrolTemplateNode;
import org.dromara.patrol.domain.bo.PatrolTemplateBo;
import org.dromara.patrol.domain.vo.PatrolTemplateVo;
import org.dromara.patrol.mapper.PatrolReportMapper;
import org.dromara.patrol.mapper.PatrolTaskMapper;
import org.dromara.patrol.mapper.PatrolTemplateMapper;
import org.dromara.patrol.mapper.PatrolTemplateNodeMapper;
import org.dromara.patrol.service.IPatrolTemplateService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 巡店管理-巡店模板配置Service业务层处理
 *
 * @author LionLi
 * @date 2024-03-25
 */
@RequiredArgsConstructor
@Service
public class PatrolTemplateServiceImpl implements IPatrolTemplateService {

    private final PatrolTemplateMapper baseMapper;

    private final PatrolTemplateNodeMapper patrolTemplateNodeMapper;

    private final PatrolReportMapper patrolReportMapper;

    private final PatrolTaskMapper patrolTaskMapper;




    /**
     * 查询巡店管理-巡店模板配置
     */
    @Override
    public PatrolTemplateVo queryById(Long templateId){
        return baseMapper.selectVoById(templateId);
    }

    /**
     * 查询巡店管理-巡店模板配置列表
     */
    @Override
    public TableDataInfo<PatrolTemplateVo> queryPageList(PatrolTemplateBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<PatrolTemplate> lqw = buildQueryWrapper(bo);
        Page<PatrolTemplateVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<PatrolTemplateVo> list = result.getRecords();
        for (PatrolTemplateVo patrolTemplateVo : list) {
            List<PatrolTemplateNode> patrolTemplateNodes = patrolTemplateNodeMapper.selectList(new LambdaQueryWrapper<PatrolTemplateNode>().
                    eq(PatrolTemplateNode::getTemplateId, patrolTemplateVo.getTemplateId()).
                    eq(PatrolTemplateNode::getIsItem, 0));
            BigDecimal score = BigDecimal.ZERO;
            for (PatrolTemplateNode patrolTemplateNode : patrolTemplateNodes) {
                BigDecimal nodeScore = patrolTemplateNode.getScore();
                if (nodeScore != null) {
                    score = score.add(nodeScore);
                }
            }
            patrolTemplateVo.setScoreCount(score);
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询巡店管理-巡店模板配置列表
     */
    @Override
    public List<PatrolTemplateVo> queryList(PatrolTemplateBo bo) {
        LambdaQueryWrapper<PatrolTemplate> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PatrolTemplate> buildQueryWrapper(PatrolTemplateBo bo) {
        Map<String, Object> params = bo.getParams();
        // 现在只需要模版名字和选择模式
        LambdaQueryWrapper<PatrolTemplate> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), PatrolTemplate::getName, bo.getName());
//        lqw.eq(StringUtils.isNotBlank(bo.getDescription()), PatrolTemplate::getDescription, bo.getDescription());
//        lqw.eq(bo.getLevel() != null, PatrolTemplate::getLevel, bo.getLevel());
//        lqw.eq(bo.getAggregateScore() != null, PatrolTemplate::getAggregateScore, bo.getAggregateScore());
        lqw.eq(StringUtils.isNotBlank(bo.getMarkStrategy()), PatrolTemplate::getMarkStrategy, bo.getMarkStrategy());
//        lqw.eq(bo.getRectifyThreshold() != null, PatrolTemplate::getRectifyThreshold, bo.getRectifyThreshold());
//        lqw.eq(bo.getItemNum() != null, PatrolTemplate::getItemNum, bo.getItemNum());
//        lqw.eq(StringUtils.isNotBlank(bo.getScoreHabit()), PatrolTemplate::getScoreHabit, bo.getScoreHabit());
//        lqw.eq(StringUtils.isNotBlank(bo.getVer()), PatrolTemplate::getVer, bo.getVer());
//        lqw.eq(StringUtils.isNotBlank(bo.getCalculateRule()), PatrolTemplate::getCalculateRule, bo.getCalculateRule());
//        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), PatrolTemplate::getStatus, bo.getStatus());
//        lqw.eq(StringUtils.isNotBlank(bo.getAllNoScoring()), PatrolTemplate::getAllNoScoring, bo.getAllNoScoring());
        return lqw;
    }

    /**
     * 新增巡店管理-巡店模板配置
     */
    @Override
    public Long insertByBo(PatrolTemplateBo bo) {
        PatrolTemplate add = MapstructUtils.convert(bo, PatrolTemplate.class);
        if (baseMapper.insert(add) == 0) {
            throw new ServiceException("添加巡店模版失败");
        }
        //添加默认分类项
        PatrolTemplateNode patrolTemplateNode = new PatrolTemplateNode();
        patrolTemplateNode.setTemplateId(add.getTemplateId());
        patrolTemplateNode.setName("所有分类");
        patrolTemplateNode.setIsItem("1");
        patrolTemplateNodeMapper.insert(patrolTemplateNode);
        return  add.getTemplateId();
    }

    /**
     * 修改巡店管理-巡店模板配置
     */
    @Override
    public Boolean updateByBo(PatrolTemplateBo bo) {
        PatrolTemplate update = MapstructUtils.convert(bo, PatrolTemplate.class);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 批量删除巡店管理-巡店模板配置
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
         //删除这个模版所有的分类和评分项目
            patrolTemplateNodeMapper.delete(new LambdaQueryWrapper<PatrolTemplateNode>().
                    in(PatrolTemplateNode::getTemplateId,ids));
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public boolean checkTemplateNameUnique(PatrolTemplateBo bo) {
        boolean exist = baseMapper.exists(new LambdaQueryWrapper<PatrolTemplate>()
                .eq(PatrolTemplate::getName, bo.getName())
                .ne(ObjectUtil.isNotNull(bo.getTemplateId()), PatrolTemplate::getTemplateId, bo.getTemplateId()));
        return !exist;
    }

    /**
     * 通过ids查询集合
     * @param ids
     * @return
     */
    @Override
    public List<PatrolTemplateVo> queryByIds(List<Long> ids) {
        return baseMapper.selectVoList(new LambdaQueryWrapper<PatrolTemplate>().in(PatrolTemplate::getTemplateId, ids));
    }

    /**
     * 检查报告是否存在
     *
     * @param templateIds
     * @return
     */
    @Override
    public boolean checkReportExist(Long[] templateIds) {
        return patrolReportMapper.exists(new LambdaQueryWrapper<PatrolReport>()
                .in(PatrolReport::getTemplateId, templateIds));
    }

    /**
     * 检查任务是否存在
     *
     * @param templateIds
     * @return
     */
    @Override
    public boolean checkTaskExist(Long[] templateIds) {
        return patrolTaskMapper.exists(new LambdaQueryWrapper<PatrolTask>()
                .in(PatrolTask::getTemplateId, templateIds));
    }
}
